const query=require('../mysql/index')
const {success,error}=require('../model/index')
const jwt=require('jsonwebtoken')
const {md5}=require('utility')

//login数据
class LoginController {
    //注册
    zcList=async (ctx)=>{
        const {username,password,nickname}=ctx.request.body;
        const isHaveSql=`select * from uses where username="${username}"`;
        const isHave=await query(isHaveSql)
        if(isHave.length){
            ctx.body=error('账号已存在')
            return
        }
        const sql=`insert into uses (username,password,nickname) values ("${username}","${md5(String(password))}","${nickname}")`
        const data=await query(sql)
        console.log(data)
        if(data.affectedRows===1){
            ctx.body=success('注册成功')
        }else{
            ctx.body=success('注册失败')
        }
    }
    //登录
    loginList=async (ctx)=>{
        const {username,password}=ctx.request.body;
        const sql=`select * from uses where username="${username}" and password="${md5(String(password))}" `
        const data=await query(sql)

        if(data.length){ 
            ctx.body=success({
                code:1,
                data:data[0],
                token:jwt.sign({id:data[0].id,username:data[0].username},'kkk')
            })
        }else{
            ctx.body=error('账号或密码错误')
        }
    }
    
}

module.exports=new LoginController()